package com.joolun.web.controller.tool;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Map;


@Slf4j
public class AccessTokenUtils {
    /**
     * 微信支付小程序APP ID
     */
    @Value("${weixin.wechat-mini-app.appId}")
    String WECHAT_MINI_APP_APP_ID;

    /**
     * 微信支付小程序APP SECRET
     */
    @Value("${weixin.wechat-mini-app.appSecret}")
    String WECHAT_MINI_APP_APP_SECRET;

    /**
     * 微信AccessToken过期时间
     */
    Integer WECHAT_ACCESS_TOKEN_EXPIRE_SECOND = 7000;

    /**
     * 微信AccessToken
     */
    String wechatAccessToken;

    /**
     * 微信AccessToken生成时间
     */
    Date wechatAccessTokenRequestTime = new Date();

    /**
     * @return 获取AccessToken
     */
    private String getAccessToken() {
        //初始化情况
        Date currentData = new Date();
        //比较时间大小
        long betweenSeconds = DateUtil.between(wechatAccessTokenRequestTime, currentData, DateUnit.SECOND);

        if (wechatAccessToken == null || betweenSeconds > WECHAT_ACCESS_TOKEN_EXPIRE_SECOND) {
            //更新AccessToken
            updateAccessToken();
            //更新获取时间
            wechatAccessTokenRequestTime = new Date();
        }

        return wechatAccessToken;
    }

    /**
     * 更新AccessToken
     */
    private void updateAccessToken() {
        JSONObject jsonObject = new JSONObject();
        try {
            String result = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token" +
                    "?grant_type=client_credential" +
                    "&appid=" + WECHAT_MINI_APP_APP_ID
                    + "&secret=" + WECHAT_MINI_APP_APP_SECRET);

            jsonObject = JSON.parseObject(result);
            wechatAccessToken = jsonObject.getString("access_token");
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }


    /**
     * 获取微信access_token
     * @param appid
     * @param secret
     * @return
     */
    public static String  getAccessToken(String appid,String secret) {
        try {
            String result = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token" +
                    "?grant_type=client_credential" +
                    "&appid=" + appid
                    + "&secret=" + secret);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String accessToken = jsonObject.getString("access_token");
            log.info("---获取access_token返回:{}",accessToken);
            return accessToken;
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return "";
    }


    /**
     *  获取加密scheme码
     *  https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/url-scheme/generateScheme.html
     * @param planId 投放计划id
     * @param processType 微信外流程类型
     * @param accessToken
     * @return
     */
    public static String getSchemeUrl(Long planId, Integer processType,String shortCode,String accessToken,String phoneNumber) {

        String url = "https://api.weixin.qq.com/wxa/generatescheme?access_token="+accessToken;

        // 通过 URL Link 进入的小程序页面路径,必须是已经发布的小程序存在的页面，不可携带 query。path 为空时会跳转小程序主页
        String path = "/pages/index/landingPage";

        JSONObject jumpWxa = new JSONObject();
        jumpWxa.put("path", path);
        jumpWxa.put("query", "planId=" + planId + "&processType=" + processType + "&course=" + shortCode+"&phoneNumber="+phoneNumber);
        //默认值"release"。要打开的小程序版本。正式版为 "release"，体验版为"trial"，开发版为"develop"，仅在微信外打开时生效
        jumpWxa.put("env_version", "release");

        JSONObject reqMap = new JSONObject();
        reqMap.put("jump_wxa", jumpWxa);

        String req = reqMap.toJSONString();
        log.info("----获取URL Scheme请求参数:{}",req);
        try {
            HttpRequest request = HttpUtil.createPost(url);
            request.contentType("application/json");
            request.body(req);
            String result = request.execute().body();
            result = URLDecoder.decode(result, "utf-8");

            log.info("微信获取scheme返回结果: {}", result);
            Map map = JSONObject.parseObject(result, Map.class);
            if (map.get("errcode").equals(0)) {
                return map.get("openlink").toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public  static void main(String []aaa){
//        String accessToken = getAccessToken("wx6dc2f5d77b3bfabf","9eaf2ad64bbd67ef960ce63fb63b0937");
//        String sss = getSchemeUrl(5L,1,"shortCode",accessToken,"");
//        System.out.println(sss);
    }
}

